//
//  RHUserBindVC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2024/10/29.
//

#import "RHUserBindVC.h"
#import "RHTools.h"

@interface RHUserBindVC ()<QMUITextFieldDelegate>

@property (nonatomic, strong) QMUITextField *nickTF;//用户名称

@property (nonatomic, strong) QMUITextField *roleTF;

@property (nonatomic, strong) QMUITextField *emailTF;

@property (nonatomic, strong) QMUITextField *phoneTF;

@property (nonatomic, strong) QMUITextField *addressTF;

@property (nonatomic, strong) RHUserModel *userModel;
@end

@implementation RHUserBindVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    self.navigationItem.title = @"绑定上级".rh_localized;
    [self setupUI];
    self.nickTF.text = nil;
}

-(void)setupUI
{
    RHUserModel *userModel = [PrivateMange share].currentUser;
    UIView *topView = kView;
    topView.layer.cornerRadius = 8;
    topView.layer.masksToBounds = YES;
    topView.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.mas_offset(15);
        make.right.mas_offset(-15);
    }];
    
    UIView *userNameView = [self itemViewWithTitle:@"用户名称".rh_localized content:userModel.superUsername showLine:NO canEdit:YES];
    self.nickTF = [userNameView viewWithTag:100];
    self.nickTF.returnKeyType = UIReturnKeyDone;
    self.nickTF.delegate = self;
    self.nickTF.placeholder = @"请输入用户名/邮箱".rh_localized;
    [topView addSubview:userNameView];
    [userNameView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.mas_offset(0);
        make.height.offset(45);
        make.bottom.mas_offset(0);
    }];
    
    QMUILabel *tipsLab = [QMUILabel labelWithText:@"已绑定设备时,该上级不可变更".rh_localized font:kSYSTEMFONT(12) textColor:kCOLOR_HEX_A(@"#171A1D", 0.6)];
    tipsLab.numberOfLines = 0;
    [self.view addSubview:tipsLab];
    tipsLab.textAlignment = NSTextAlignmentLeft;
    [tipsLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(topView);
        make.top.equalTo(topView.mas_bottom).offset(10);
    }];
    
    
    UIView *botView = kView;
    botView.layer.cornerRadius = 8;
    botView.layer.masksToBounds = YES;
    botView.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:botView];
    [botView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(tipsLab.mas_bottom).offset(10);
        make.left.right.equalTo(topView);
    }];
    
    
    UIView *roleView = [self itemViewWithTitle:@"用户角色".rh_localized content:nil showLine:YES canEdit:NO];
    self.roleTF = [roleView viewWithTag:100];
    [botView addSubview:roleView];
    [roleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.mas_offset(0);
        make.height.offset(45);
    }];
    
    
    UIView *emailView = [self itemViewWithTitle:@"用户邮箱".rh_localized content:nil showLine:YES canEdit:NO];
    self.emailTF = [emailView viewWithTag:100];
    [botView addSubview:emailView];
    [emailView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(roleView.mas_bottom);
        make.height.offset(45);
    }];
    
    UIView *contactView = [self itemViewWithTitle:@"联系方式".rh_localized content:nil showLine:YES canEdit:NO];
    self.phoneTF = [contactView viewWithTag:100];
    [botView addSubview:contactView];
    [contactView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(emailView.mas_bottom);
        make.height.offset(45);
    }];
    
    UIView *adressView = [self itemViewWithTitle:@"用户地址".rh_localized content:nil showLine:NO canEdit:NO];
    self.addressTF = [adressView viewWithTag:100];
    [botView addSubview:adressView];
    [adressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(contactView.mas_bottom);
        make.height.offset(45);
        make.bottom.mas_offset(0);
    }];
    
    
    QMUIButton *sureBtn = [[QMUIButton alloc]init];
    [sureBtn setTitle:@"确认绑定".rh_localized forState:UIControlStateNormal];
    [sureBtn setTitleColor:kCOLOR_HEX(@"ffffff") forState:UIControlStateNormal];
    [sureBtn setCornerRadius:8];
    sureBtn.backgroundColor = CMainColorGreen;
    [sureBtn addTarget:self action:@selector(bindToSuper) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sureBtn];
    
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.offset(50);
        make.bottom.mas_offset(kSafe_bottom>0?-kSafe_bottom:-15);
    }];
}

-(UIView*)itemViewWithTitle:(NSString*)title content:(NSString *)content showLine:(BOOL)showLine canEdit:(BOOL)canEdit
{
    UIView *bgView = kView;
    QMUILabel *titleLab = [QMUILabel labelWithText:title font:kSYSTEMFONT(14) textColor:kCOLOR_HEX_A(@"#171A1D", 0.8)];
    titleLab.numberOfLines = 2;
    titleLab.adjustsFontSizeToFitWidth = YES;
    titleLab.minimumScaleFactor = 0.8;
    titleLab.textAlignment = NSTextAlignmentLeft;
    [bgView addSubview:titleLab];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(0);
        make.centerY.mas_offset(0);
        make.width.lessThanOrEqualTo(@(100));
    }];
    
    QMUITextField *textField = [[QMUITextField alloc]init];
    textField.textColor = kCOLOR_HEX(@"#171A1D");
    textField.tag = 100;
    textField.placeholderColor = kCOLOR_HEX_A(@"#171A1D", 0.25);
    textField.userInteractionEnabled = canEdit;
    textField.font = kSYSTEMFONT(14);
    [bgView addSubview:textField];
    textField.text = content;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
 
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleLab.mas_right).offset(5);
        make.right.mas_offset(0);
        make.centerY.mas_offset(0);
        make.height.offset(40);
    }];
    if (showLine) {
        UIView *line = kView;
        line.backgroundColor = kCOLOR_HEX(@"#EBEDF0");
        [bgView addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(titleLab);
            make.bottom.mas_offset(0);
            make.right.equalTo(textField);
            make.height.offset(1);
        }];
    }
    
    if (canEdit) {
        textField.placeholder = @"请输入新用户名称".rh_localized;
         
    }
    return bgView;
}

-(void)getSuperUserInfo
{
    [QMUITips showLoadingInView:kApplication.keyWindow];
    NSDictionary *para = @{@"username":self.nickTF.text};
    [BaseModel startGetWithCompletionAPIKey:H_getUserInfo argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            self.userModel = [RHUserModel yy_modelWithJSON:request.responseJSONObject[@"data"]];
            [self updateUIWithModel:self.userModel];

        }
        
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                
    }];
}
-(void)updateUIWithModel:(RHUserModel*)userModel
{
    NSString *role = [RHTools getRoleContentWithType:userModel.orgType brandId:userModel.brandId];
    self.roleTF.text = role;
    self.emailTF.text = userModel.email;
    self.phoneTF.text = userModel.phonenumber;
    self.addressTF.text = userModel.address;
}


-(void)bindToSuper
{
    if (self.nickTF.text.length == 0) {
        [QMUITips showInfo:@"请输入用户名/邮箱".rh_localized];
        return;
    }
    if (self.userModel.email.length == 0) {
        [QMUITips showInfo:@"用户不存在".rh_localized];
        return;
    }
    [QMUITips showLoadingInView:kApplication.keyWindow];
    NSDictionary *para = @{@"sendEmail":ValidNullData(self.userModel.email),
                           @"userId":@(self.userModel.userId)};
    [BaseModel startWithCompletionAPIKey:H_bindSuper argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            
            [QMUITips showSucceed:@"绑定用户成功".rh_localized inView:self.view hideAfterDelay:1];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                //绑定成功后获取一下个人信息,根据角色重新加载对应控制器
                [QMUITips showLoadingInView:kAppWindow];
                [[PrivateMange share]getUserInfoSuccess:^(RHUserModel * _Nonnull userModel) {
                    [[NSNotificationCenter defaultCenter]postNotificationName:UserRoleDidChangeNotification object:nil];
                }];
            });
        }
        
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                
    }];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField.text.length>0) {
        [self getSuperUserInfo];
    }
    
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
  
    [textField endEditing:YES];
    return YES;
}

@end
